import React from 'react'
import { Search } from 'react-vant'
import './style.css'
import axios from 'axios'
class Index extends React.PureComponent {
  state = {
    searchHistory: JSON.parse(localStorage.getItem('searchHistory')) ||  [],
    list: []
  }
  fetchList = async (q) => {
    const resp = await axios.get('/api/list?q=' + q,)
    this.setState({
      list: resp.data.data
    })
  } 
  handleSearch = (q) => {
    const { searchHistory } = this.state
    // 本地存储
    this.setState({
      searchHistory: [...new Set([q, ...searchHistory])] /* 去重复 */
    })
    // 请求搜索数据
    this.fetchList(q)
  }
  handleDelete = (value) => {
    const { searchHistory } = this.state
    // 过滤删除
    const newSearchHistory = searchHistory.filter(v => v !== value);
    this.setState({
      searchHistory: newSearchHistory
    })
  }
  handleClear = () => {
    this.setState({
      searchHistory: []
    })
  }
  render() {
    const { searchHistory, list } = this.state
    return (
      <div>
        <Search onSearch={this.handleSearch}></Search>
        <div className="search-history">
          <h2>
            <span>历史记录</span>
            <span className='clear' onClick={() => this.handleClear()}>清空</span>
          </h2>
          <div className="box">
            {
              searchHistory.map((v, i) => {
                return <div key={i}>
                  {v}
                  <span onClick={() => this.handleDelete(v)}>X</span>
                </div>
              })
            }
          </div>
        </div>
        <div className="list">
            {
              list.map((v, i) => {
                return (
                  <dl key={i}>
                    <dt>
                      <img src={v.image} alt="" />
                    </dt>
                    <dd>
                      <h3>{v.title}</h3>
                      <p>{v.desc}</p>
                    </dd>
                  </dl>  
                )
              })
            }
        </div>
      </div>  
    )
  }
  // 更新
  componentDidUpdate() {
    localStorage.setItem('searchHistory', JSON.stringify(this.state.searchHistory))
  }
}

export default Index